package controller

import (
	"booksPro/dao"
	"booksPro/model"
	"booksPro/utils"
	"fmt"
	"net/http"
	"text/template"
)

// login 处理用户登陆的函数
func Login(w http.ResponseWriter, r *http.Request) {
	//先判断是否已经登录
	_, flag := dao.IsLogin(r)
	if flag {
		//已经登录,直接去首页
		GetBooksByPrice(w, r)
	} else {
		//没有登录 才去做登录的逻辑，并设置sesionId 入库 和cookie给浏览器
		//获取用户名和密码
		username := r.PostFormValue("username")
		password := r.PostFormValue("password")
		user, _ := dao.CheckUserAndPassword(username, password)
		// if user != nil { //这里有坑，user ！=nil不行， 因为user的id属性是int类型，有么默认值0， 所以user永远不会是nil
		if user.ID > 0 {
			fmt.Println("用户名和密码正确")
			//创建session 和Cookie
			uuid := utils.CreateUUID()
			session := &model.Session{
				SessionID: uuid,
				Username:  user.Username,
				UserID:    user.ID,
			}
			//把 Session保存到数据库
			dao.AddSession(session)
			cookie := http.Cookie{
				Name:     "userId",
				Value:    uuid,
				HttpOnly: true,
			}
			//设置Cookie 与Session相关联    让Cookie的 value  = SessionID
			http.SetCookie(w, &cookie)
			t := template.Must(template.ParseFiles("views/pages/user/login_success.html"))
			t.Execute(w, user)
		} else {
			fmt.Println("用户名和密码错误")
			t := template.Must(template.ParseFiles("views/pages/user/login.html"))
			t.Execute(w, "用户名和密码错误")
		}
	}
}

func Logout(w http.ResponseWriter, r *http.Request) {
	//获取Cookie
	cookie, _ := r.Cookie("userId")
	if cookie != nil {
		cookieValue := cookie.Value
		//根据SessionId  =  Cookie的value  删除Sessions表里的 记录
		dao.DeleteSession(cookieValue)
		//让Cookie失效  <0立即失效s
		cookie.MaxAge = -1
		//将重新设置的cookie重新发给浏览器，
		http.SetCookie(w, cookie)
	}
	GetBooksByPrice(w, r)
}

// regist
func Regist(w http.ResponseWriter, r *http.Request) {
	//获取用户名
	username := r.PostFormValue("username")
	password := r.PostFormValue("password")
	email := r.PostFormValue("email")
	user := dao.CheckUsername(username)
	if user.ID > 0 {
		// json, _ := json.Marshal("注册失败，重复用户名")
		fmt.Println("注册失败，重复用户名")
		t := template.Must(template.ParseFiles("views/pages/user/regist.html"))
		t.Execute(w, "用户名已存在！")
	} else {
		dao.SaveUser(username, password, email)
		t := template.Must(template.ParseFiles("views/pages/user/regist_success.html"))
		t.Execute(w, "注册成功 ")
	}
}

// 通过发送的Ajax请求 验证用户名是否已经被创建
func CheckUserName(w http.ResponseWriter, r *http.Request) {
	username := r.PostFormValue("username")
	fmt.Println("传入的用户名是", username)
	user := dao.CheckUsername(username)
	if user.ID > 0 {
		w.Write([]byte("用户名已存在"))
	} else {
		w.Write([]byte("<font style='color:green'>用户名可用</font>"))
	}
}
